package com.fishery.authority.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.authority.entity.Role;
import com.fishery.authority.entity.RoleBase;
import com.fishery.authority.mapper.RoleMapper;
import com.fishery.authority.mapper.UserMapper;
import com.fishery.authority.service.RoleBaseService;
import com.fishery.authority.service.RoleService;
import com.fishery.authority.utils.SecurityContextUtil;
import com.fishery.entity.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 711
 * @since 2021-01-13
 */
@RestController
@CrossOrigin
@RequestMapping("/authority/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleBaseService roleBaseService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

//    /**
//     * 分页查询接口
//     * @param current
//     * @param limit
//     * @return
//     */
//    @ApiOperation(value = "分页获取角色")
//    @PreAuthorize("hasAnyAuthority('authority','authority_role')")
//    @GetMapping("{current}/{limit}")
//    public Result index(
//            @ApiParam(name = "current", value = "当前页码", required = true)
//            @PathVariable Long current,
//            @ApiParam(name = "limit", value = "每页记录数", required = true)
//            @PathVariable Long limit) {
//        limit = limit <= 0 ? 5 : limit;
//        current = current <= 0 ? 1 : current;
//        Page<Role> page = new Page<>(current, limit);
//        QueryWrapper<Role> wrapper = new QueryWrapper<>();
//        roleService.page(page,wrapper);
//        return Result.success().data(page);
//    }

    /**
     * 分页查询接口
     *
     * @param start
     * @param end
     * @param baseId
     * @return
     */
    @ApiOperation(value = "分页获取角色")
    @PreAuthorize("hasAnyAuthority('authority','authority_role')")
    @GetMapping("/{baseId}/{start}/{end}")
    public Result index(@PathVariable(name = "start") @ApiParam(required = true, value = "尺寸") Integer start,
                        @PathVariable(name = "end") @ApiParam(required = true, value = "当前页码") Integer end,
                        @PathVariable(name = "baseId") @ApiParam(required = true, value = "基地id") String baseId) {
        Map map = roleBaseService.sliceListAchievePageSelectBaseDeRole(start, end, baseId);
        return Result.success().data(map);
    }

    /**
     * 不分页查询接口
     *
     * @param baseId
     * @return
     */
    @ApiOperation(value = "不分页获取角色")
    @PreAuthorize("hasAnyAuthority('authority','authority_role')")
    @GetMapping("noPage/{baseId}")
    public Result indexRoleBaseNoPage(@PathVariable(name = "baseId") @ApiParam(required = true, value = "基地id") String baseId) {
        List<Role> roles = roleBaseService.SelectBaseDeRole(baseId);
        return Result.success().data(roles);
    }

    /**
     * 根据id获取角色接口
     * @param id
     * @return
     */
    @ApiOperation(value = "查询角色")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "id", value = "roleID", required = true, dataType = "String")
//    })
    @PreAuthorize("hasAnyAuthority('authority','authority_role')")
    @GetMapping("get/{id}")
    public Result get(@PathVariable String id) {
        if(StringUtils.isEmpty(id)) {
            return Result.success("请输入id");
        }
        Role role = roleService.findById(id);
        return Result.success().data(role);
    }

    /**
     * 根据id获取角色接口
     * @param userId
     * @return
     */
    @ApiOperation(value = "通过userId查询角色")
    @PreAuthorize("hasAnyAuthority('authority','authority_role')")
    @GetMapping("getByUserId/{userId}")
    public Result getByUserId(@PathVariable String userId) {
        if(StringUtils.isEmpty(userId)) {
            return Result.success("请输入正确的id");
        }
        List<Role> roles = roleService.findRoleByUserId(userId);
        return Result.success().data(roles);
    }

    /**
     * 新增角色接口
     * @param role
     * @return
     */
    @ApiOperation(value = "新增角色")
    @PreAuthorize("hasAnyAuthority('authority_role_add')")
    @PostMapping("save")
    public Result save(@RequestBody Role role, String baseId) {
        List<Role> oldRoleList = roleMapper.selectSameRoleName(baseId, role.getName());
        if(oldRoleList.size() != 0) {
            return Result.error("添加失败，该角色名已存在");
        }
        boolean result = roleService.save(role);
        RoleBase newrole = new RoleBase();
        newrole.setBaseId(baseId);
        newrole.setRoleId(role.getId());
        boolean ret = roleBaseService.baseCreateNewRole(newrole);
        return result && ret ? Result.success() : Result.error();
    }

    /**
     * 修改角色接口
     * @param role
     * @return
     */
    @ApiOperation(value = "修改角色")
//    @PreAuthorize("hasAnyAuthority('authority_role_update')")
    @PutMapping("update")
    public Result updateById(@RequestBody Role role) {
        if(role == null || StringUtils.isEmpty(role.getId())) {
            return Result.error("roleId不能为空");
        }
        boolean result = roleService.updateById(role);
        int i = 0;
        return result ? Result.success() : Result.error();
    }

    /**
     * 根据id删除角色接口
     * @param id
     * @return
     */
    @ApiOperation(value = "删除角色")
    @PreAuthorize("hasAnyAuthority('authority_role_delete')")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable String id) {
        if (id == null) {
            return Result.error();
        }
        boolean result = roleService.removeById(id);
        return result ? Result.success() : Result.error();
    }

    /**
     * 批量删除角色
     * @param idList
     * @return
     */
    @ApiOperation(value = "根据id列表删除角色")
    @DeleteMapping("batchRemove")
    public Result batchRemove(@RequestBody List<String> idList) {
        if (idList == null) {
            return Result.error();
        }
        boolean result = roleService.removeByIds(idList);
        return result ? Result.success() : Result.error();
    }

    /**
     * 修改用户对应的角色（该角色已存在）
     * @param roleId
     * @return
     */
    @ApiOperation(value = "修改用户对应的角色（该角色已存在）")
    @PreAuthorize("hasAnyAuthority('authority_role_update')")
    @PutMapping("updateUserRole")
    public Result updateUserRole(String userId, String roleId) {
        if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(userId)) {
            return Result.error("roleId、userId不能为空");
        }
        userMapper.updateRoleAndUser(userId, roleId);
        return Result.success();
    }
}

